package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.Census;
import com.ruoyi.business.domain.Orders;
import com.ruoyi.business.domain.ServiceType;
import com.ruoyi.business.service.ICensusService;
import com.ruoyi.business.service.IServiceTypeService;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.metrics.Sum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CensusServiceImpl implements ICensusService {
    @Resource
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private IServiceTypeService iServiceTypeService;

//    具体日期查总收入分布
    @Override
    public Census selectCensus(String id,String date) {

        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        queryBuilder.addAggregation(AggregationBuilders.terms("by_merchant").field("mid")
                .subAggregation(AggregationBuilders.dateHistogram("by_date")
                        .field("order_time")
                        .calendarInterval(DateHistogramInterval.DAY)
                        .format("yyyy-MM-dd")
                        .subAggregation(AggregationBuilders.sum("total_price")
                                .field("price"))));
        // 执行查询
        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(),
                Orders.class, IndexCoordinates.of("orders"));
        // 获取聚合结果
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();

        // 获取第一层聚合的结果对象
        ParsedLongTerms byMerchant = aggregations.get("by_merchant");

        // 创建Census对象
        Census censusEntry = new Census();
        if (id == null || date ==null){
            censusEntry.setOrderCount(0L);
            censusEntry.setTakein(0.0);
        }
        // 获取商家桶的Buckets
        if (byMerchant != null) {
            byMerchant.getBuckets().forEach(merchantBucket -> {
                String keyAsString1 = merchantBucket.getKeyAsString();
                String merchantId = id.toString();
                if (merchantId.equals(keyAsString1)){
                // 获取日期直方图聚合结果
                Histogram dateHistogram = merchantBucket.getAggregations().get("by_date");
                if (dateHistogram != null) {
                    dateHistogram.getBuckets().forEach(histogramBucket -> {
                        String keyAsString = histogramBucket.getKeyAsString();
                        if (keyAsString.equals(date)) {
                            long docCount = histogramBucket.getDocCount();
                            Sum sumPrice = histogramBucket.getAggregations().get("total_price");
                            if (sumPrice != null) {
                                double priceValue = sumPrice.getValue();
                                // 设置Census对象的属性
                                censusEntry.setMerchantId(Long.parseLong(merchantBucket.getKeyAsString()));
                                censusEntry.setOrderCount(docCount);
                                censusEntry.setTakein(priceValue);
                            }
                        }
                    });
                }
            }
            });
        }

        return censusEntry;
    }
    @Override
    public List<Map<String, String>>  serviceType(String typeid, String typedate) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 构建查询
        queryBuilder.addAggregation(
                AggregationBuilders.terms("by_merchant").field("mid")
                        .subAggregation(
                                AggregationBuilders.dateHistogram("by_date")
                                        .field("order_time")
                                        .calendarInterval(DateHistogramInterval.DAY)
                                        .format("yyyy-MM-dd")
                                        .subAggregation(
                                                AggregationBuilders.terms("serviceType").field("service_type_id")
                                                        .subAggregation(
                                                                AggregationBuilders.sum("total_price").field("price")
                                                        )
                                        )
                        )
        );
        // 执行查询
        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(),
                Orders.class, IndexCoordinates.of("orders"));
        // 获取聚合结果
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
        // 获取第一层聚合的结果对象
        ParsedLongTerms byMerchant = aggregations.get("by_merchant");



        //创建一个数组存总价格
        List<Map<String, String>> list = new ArrayList<>();
        if (typeid == null || typedate ==null){
            Map<String, String> map = new HashMap<>();
            map.put("service", "");
            map.put("count", String.valueOf(0));
            map.put("name", "");
            map.put("value", String.valueOf(0));
            list.add(map);

        }
        // 获取商家桶的Buckets
        if (byMerchant != null) {
            byMerchant.getBuckets().forEach(merchantBucket -> {
                String keyAsString1 = merchantBucket.getKeyAsString();
                String merchantId = typeid.toString();
                if (merchantId.equals(keyAsString1)) {
                    // 获取日期直方图聚合结果
                    ParsedDateHistogram dateHistogram = merchantBucket.getAggregations().get("by_date");
                    if (dateHistogram != null) {
                        dateHistogram.getBuckets().forEach(histogramBucket -> {
                            String keyAsString = histogramBucket.getKeyAsString();
                            if (keyAsString.equals(typedate)) {
                                ParsedLongTerms serviceTypes = histogramBucket.getAggregations().get("serviceType");
                                if (serviceTypes != null) {
                                    serviceTypes.getBuckets().forEach(serviceType -> {
                                        String s = serviceType.getKey().toString();
                                        ServiceType type1 = iServiceTypeService.selectServiceTypeById(Long.valueOf(s));
//                                        类型名字
                                        String service = type1.getName();
//                                        类型总订单
                                        String docCount = String.valueOf(serviceType.getDocCount());
                                        Sum totalSum = serviceType.getAggregations().get("total_price");
                                        String value = null;
                                        if (totalSum != null) {
                                            value = String.valueOf(totalSum.getValue());
                                        }
                                        Map<String, String> map = new HashMap<>();
                                        map.put("service", service);
                                        map.put("count", docCount);
                                        map.put("name", service);
                                        map.put("value", value);
                                        list.add(map);
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        System.out.println(list);
        return list;
    }




    // 按照月查总收入分布
    @Override
    public Census selectMonths(String id, String month) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        queryBuilder.addAggregation(AggregationBuilders.terms("by_merchant").field("mid")
                .subAggregation(AggregationBuilders.dateHistogram("by_date")
                        .field("order_time")
                        .calendarInterval(DateHistogramInterval.MONTH)
                        .format("MM")
                        .subAggregation(AggregationBuilders.sum("total_price")
                                .field("price"))));
        // 执行查询
        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(),
                Orders.class, IndexCoordinates.of("orders"));
        // 获取聚合结果
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();

        // 获取第一层聚合的结果对象
        ParsedLongTerms byMerchant = aggregations.get("by_merchant");

        // 创建Census对象
        Census censusEntry = new Census();
        if (id == null || month ==null){
            censusEntry.setOrderCount(0L);
            censusEntry.setTakein(0.0);
        }
        // 获取商家桶的Buckets
        if (byMerchant != null) {
            byMerchant.getBuckets().forEach(merchantBucket -> {
                String keyAsString1 = merchantBucket.getKeyAsString();
                String merchantId = id.toString();
                if (merchantId.equals(keyAsString1)){
                    // 获取日期直方图聚合结果
                    Histogram dateHistogram = merchantBucket.getAggregations().get("by_date");
                    if (dateHistogram != null) {
                        dateHistogram.getBuckets().forEach(histogramBucket -> {
                            String keyAsString = histogramBucket.getKeyAsString();
                            if (keyAsString.equals(month)) {
                                long docCount = histogramBucket.getDocCount();
                                Sum sumPrice = histogramBucket.getAggregations().get("total_price");
                                if (sumPrice != null) {
                                    double priceValue = sumPrice.getValue();
                                    // 设置Census对象的属性
                                    censusEntry.setMerchantId(Long.parseLong(merchantBucket.getKeyAsString()));
                                    censusEntry.setOrderCount(docCount);
                                    censusEntry.setTakein(priceValue);
                                }
                            }
                        });
                    }
                }
            });
        }

        return censusEntry;
    }
    @Override
    public List<Map<String, String>> serviceMonth(String typeid, String monthdate) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 构建查询
        queryBuilder.addAggregation(
                AggregationBuilders.terms("by_merchant").field("mid")
                        .subAggregation(
                                AggregationBuilders.dateHistogram("by_date")
                                        .field("order_time")
                                        .calendarInterval(DateHistogramInterval.MONTH)
                                        .format("MM")
                                        .subAggregation(
                                                AggregationBuilders.terms("serviceType").field("service_type_id")
                                                        .subAggregation(
                                                                AggregationBuilders.sum("total_price").field("price")
                                                        )
                                        )
                        )
        );
        // 执行查询
        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(),
                Orders.class, IndexCoordinates.of("orders"));
        // 获取聚合结果
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
        // 获取第一层聚合的结果对象
        ParsedLongTerms byMerchant = aggregations.get("by_merchant");



        //创建一个数组存总价格
        List<Map<String, String>> list = new ArrayList<>();
        if (typeid == null || monthdate ==null){
            Map<String, String> map = new HashMap<>();
            map.put("service", "");
            map.put("count", String.valueOf(0));
            map.put("name", "");
            map.put("value", String.valueOf(0));
            list.add(map);

        }
        // 获取商家桶的Buckets
        if (byMerchant != null) {
            byMerchant.getBuckets().forEach(merchantBucket -> {
                String keyAsString1 = merchantBucket.getKeyAsString();
                String merchantId = typeid.toString();
                if (merchantId.equals(keyAsString1)) {
                    // 获取日期直方图聚合结果
                    ParsedDateHistogram dateHistogram = merchantBucket.getAggregations().get("by_date");
                    if (dateHistogram != null) {
                        dateHistogram.getBuckets().forEach(histogramBucket -> {
                            String keyAsString = histogramBucket.getKeyAsString();
                            if (keyAsString.equals(monthdate)) {
                                ParsedLongTerms serviceTypes = histogramBucket.getAggregations().get("serviceType");
                                if (serviceTypes != null) {
                                    serviceTypes.getBuckets().forEach(serviceType -> {
                                        String s = serviceType.getKey().toString();
                                        ServiceType type1 = iServiceTypeService.selectServiceTypeById(Long.valueOf(s));
//                                        类型名字
                                        String service = type1.getName();
//                                        类型总订单
                                        String docCount = String.valueOf(serviceType.getDocCount());
                                        Sum totalSum = serviceType.getAggregations().get("total_price");
                                        String value = null;
                                        if (totalSum != null) {
                                            value = String.valueOf(totalSum.getValue());
                                        }
                                        Map<String, String> map = new HashMap<>();
                                        map.put("service", service);
                                        map.put("count", docCount);
                                        map.put("name", service);
                                        map.put("value", value);
                                        list.add(map);
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        System.out.println(list);
        return list;
    }







    // 按照年查总收入分布
    @Override
    public Census selectYear(String id, String year) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        queryBuilder.addAggregation(AggregationBuilders.terms("by_merchant").field("mid")
                .subAggregation(AggregationBuilders.dateHistogram("by_date")
                        .field("order_time")
                        .calendarInterval(DateHistogramInterval.YEAR)
                        .format("yyyy")
                        .subAggregation(AggregationBuilders.sum("total_price")
                                .field("price"))));
        // 执行查询
        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(),
                Orders.class, IndexCoordinates.of("orders"));
        // 获取聚合结果
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();

        // 获取第一层聚合的结果对象
        ParsedLongTerms byMerchant = aggregations.get("by_merchant");

        // 创建Census对象
        Census censusEntry = new Census();
        if (id == null || year ==null){
            censusEntry.setOrderCount(0L);
            censusEntry.setTakein(0.0);
        }
        // 获取商家桶的Buckets
        if (byMerchant != null) {
            byMerchant.getBuckets().forEach(merchantBucket -> {
                String keyAsString1 = merchantBucket.getKeyAsString();
                String merchantId = id.toString();
                if (merchantId.equals(keyAsString1)){
                    // 获取日期直方图聚合结果
                    Histogram dateHistogram = merchantBucket.getAggregations().get("by_date");
                    if (dateHistogram != null) {
                        dateHistogram.getBuckets().forEach(histogramBucket -> {
                            String keyAsString = histogramBucket.getKeyAsString();
                            if (keyAsString.equals(year)) {
                                long docCount = histogramBucket.getDocCount();
                                Sum sumPrice = histogramBucket.getAggregations().get("total_price");
                                if (sumPrice != null) {
                                    double priceValue = sumPrice.getValue();
                                    // 设置Census对象的属性
                                    censusEntry.setMerchantId(Long.parseLong(merchantBucket.getKeyAsString()));
                                    censusEntry.setOrderCount(docCount);
                                    censusEntry.setTakein(priceValue);
                                }
                            }
                        });
                    }
                }
            });
        }

        return censusEntry;
    }
    @Override
    public List<Map<String, String>> serviceYear(String typeid, String yeardate) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 构建查询
        queryBuilder.addAggregation(
                AggregationBuilders.terms("by_merchant").field("mid")
                        .subAggregation(
                                AggregationBuilders.dateHistogram("by_date")
                                        .field("order_time")
                                        .calendarInterval(DateHistogramInterval.YEAR)
                                        .format("yyyy")
                                        .subAggregation(
                                                AggregationBuilders.terms("serviceType").field("service_type_id")
                                                        .subAggregation(
                                                                AggregationBuilders.sum("total_price").field("price")
                                                        )
                                        )
                        )
        );
        // 执行查询
        SearchHits<Orders> searchHits = restTemplate.search(queryBuilder.build(),
                Orders.class, IndexCoordinates.of("orders"));
        // 获取聚合结果
        Aggregations aggregations = (Aggregations) searchHits.getAggregations().aggregations();
        // 获取第一层聚合的结果对象
        ParsedLongTerms byMerchant = aggregations.get("by_merchant");



        //创建一个数组存总价格
        List<Map<String, String>> list = new ArrayList<>();
        if (typeid == null || yeardate ==null){
            Map<String, String> map = new HashMap<>();
            map.put("service", "");
            map.put("count", String.valueOf(0));
            map.put("name", "");
            map.put("value", String.valueOf(0));
            list.add(map);

        }
        // 获取商家桶的Buckets
        if (byMerchant != null) {
            byMerchant.getBuckets().forEach(merchantBucket -> {
                String keyAsString1 = merchantBucket.getKeyAsString();
                String merchantId = typeid.toString();
                if (merchantId.equals(keyAsString1)) {
                    // 获取日期直方图聚合结果
                    ParsedDateHistogram dateHistogram = merchantBucket.getAggregations().get("by_date");
                    if (dateHistogram != null) {
                        dateHistogram.getBuckets().forEach(histogramBucket -> {
                            String keyAsString = histogramBucket.getKeyAsString();
                            if (keyAsString.equals(yeardate)) {
                                ParsedLongTerms serviceTypes = histogramBucket.getAggregations().get("serviceType");
                                if (serviceTypes != null) {
                                    serviceTypes.getBuckets().forEach(serviceType -> {
                                        String s = serviceType.getKey().toString();
                                        ServiceType type1 = iServiceTypeService.selectServiceTypeById(Long.valueOf(s));
//                                        类型名字
                                        String service = type1.getName();
//                                        类型总订单
                                        String docCount = String.valueOf(serviceType.getDocCount());
                                        Sum totalSum = serviceType.getAggregations().get("total_price");
                                        String value = null;
                                        if (totalSum != null) {
                                            value = String.valueOf(totalSum.getValue());
                                        }
                                        Map<String, String> map = new HashMap<>();
                                        map.put("service", service);
                                        map.put("count", docCount);
                                        map.put("name", service);
                                        map.put("value", value);
                                        list.add(map);
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
        System.out.println(list);
        return list;
    }


}
